import { defineEventHandler, getQuery, createError, sendRedirect, setCookie } from "h3";
import { UserService } from "../../../services/userService";
import { saveToken } from "../../../utils/jwt";

export default defineEventHandler(async (event) => {
  const query = getQuery(event);
  const { code } = query;

  if (!code) {
    throw createError({
      statusCode: 400,
      statusMessage: "Authorization code is required",
    });
  }

  const config = useRuntimeConfig();

  try {
    // 交换授权码获取访问令牌
    const tokenResponse = await $fetch("https://oauth2.googleapis.com/token", {
      method: "POST",
      body: {
        client_id: process.env.GOOGLE_CLIENT_ID,
        client_secret: process.env.GOOGLE_CLIENT_SECRET,
        code,
        grant_type: "authorization_code",
        redirect_uri: `${process.env.BASE_URL}/api/auth/google/callback`,
      },
    });

    // 获取用户信息
    const userInfo = await $fetch("https://www.googleapis.com/oauth2/v2/userinfo", {
      headers: {
        Authorization: `Bearer ${tokenResponse.access_token}`,
      },
    });

    let user = await UserService.findByGoogleId(userInfo.id);

    if (!user) {
      // 检查是否已有相同邮箱的用户
      const existingUser = await UserService.findByEmail(userInfo.email);
      if (existingUser) {
        // 关联Google账号
        user = await UserService.updateUser(existingUser.id, {
          googleId: userInfo.id,
          avatar: userInfo.picture,
        });
      } else {
        // 创建新用户
        user = await UserService.createUser({
          email: userInfo.email,
          name: userInfo.name,
          googleId: userInfo.id,
          avatar: userInfo.picture,
        });
      }
    }
    saveToken(event, user)

    // 重定向到前端
    return sendRedirect(event, `${process.env.FRONTEND_URL}/secure/dashboard`);
  } catch (error) {
    console.error("Google OAuth error:", error);
    return sendRedirect(event, `${process.env.FRONTEND_URL}/auth/callback?error=oauth_failed`);
  }
});